#ParallelPlatform Project - A web platform to distribute and share knowledge
#Copyright (C) 2011  Daniel Guerrero Martinez & Sergio Rodriguez Lumley
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
#from django.db.models import Max
#from datetime import datetime
from uuid import uuid1
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import ugettext as _
#from transmeta import TransMeta #this makes it possible to translate attribute to model
from django.contrib.auth.models import User


class Page(models.Model):
    
    uuid = models.CharField( max_length=60, null=False,blank=False)
    onCreate = models.DateTimeField(auto_now = False,auto_now_add=True)
    valid = models.BooleanField(default=True)
    editable = models.BooleanField(default=True)
    newChildren = models.BooleanField(default=True)
    type = models.PositiveSmallIntegerField(null=True)
    siblingPosition = models.PositiveSmallIntegerField(null=True)
    #wiki = models.ForeignKey( Wiki, related_name='pages')
    father = models.ForeignKey( 'self', related_name='children', null=True)
    #current = models.OneToOneField('PageRevision',related_name='current',null=True)
    revisionAvaible = {}
    
    collaborators = models.ManyToManyField(User, through='Collaborator',related_name="collaborated_page")
    
    def __init__(self, *args, **kwargs): 
        super(Page, self).__init__(*args, **kwargs)
        if self.uuid is not '' and self.uuid is not None:
            self.revisionAvaible = {}
            for lang in settings.LANGUAGES:
                rev = self.revision.filter(lang=lang[0])
                if len(rev) != 0:
                    self.revisionAvaible[lang[0]] = rev.order_by('-version')[0]
    
    def getCurrent(self, lang=None, version=None):
        if lang is None:
            lang = get_language()
        
        if version is None:
            if lang in self.revisionAvaible:
                return self.revisionAvaible[lang]
            else:
                return None
        else:
            try:
                return self.revision.filter(lang=lang).get(version=int(version))
            except:
                return None
        
    def getRevisionValid(self, lang=None):
        rev = self.getCurrent(lang=lang)
        if rev is None:
            for lang in self.revisionAvaible:
                return self.revisionAvaible[lang]

        return rev
    def getLangValid(self):
        languages = []
        for lang in settings.LANGUAGES:
            if lang[0] in self.revisionAvaible:
                languages.append(lang)
        return languages
                
    def __unicode__(self):
        return self.getRevisionValid().title
    
    def previousSibling(self):
        try: 
            return self.father.children.get(siblingPosition=self.siblingPosition-1)
        except:
            return None
    
    def nextSibling(self):
        try: 
            return self.father.children.get(siblingPosition=self.siblingPosition+1)
        except:
            return None
    
    def newRevision(self, pageRev, user):
        self.save(pageRev)
        collaborator = Collaborator(user=user,page=self,version=pageRev.version,lang=pageRev.lang)
        collaborator.save()
    
    def save(self, pageRev = None):
        if self.uuid is '' or self.uuid is None:
            while True:
                id = str(uuid1())
                try:
                    Page.objects.get(name=id)
                except:
                    self.uuid = id
                    break
        
        super(Page,self).save()
        
        if self.siblingPosition is None and self.father is not None:
            self.siblingPosition= len(self.father.children.all())
        
        currentVersion = self.revision.filter(lang=get_language())
        
        if pageRev == None:# Not new revision
            if len(currentVersion) == 0:#And are not revision, create default revision
                pageRev = PageRevision(title=_("Title of the main page"),
                                                lang=get_language(),
                                                content=_("The webpage has been created (probably recently) without any information to show. Be the first to complete it!"),
                                                #noteChange="This is the automatic initial version",
                                                page=self,
                                                version=0)
                pageRev.save()
                #self.current = pageRev

        else:
            if len(currentVersion) > 0:
                currentVersion = currentVersion.order_by('-version')[0].version
            else:
                currentVersion = 0;
            pageRev.version = currentVersion+1
            pageRev.lang = get_language()
            pageRev.page=self
            pageRev.save()
            #self.current = pageRev     
            
        super(Page,self).save()
    
    def getPath(self):
        url="/"+self.uuid+"/"
        return url
    
    def erase(self):
        for son in self.children.all(): 
            son.erase()
        self.revision.all().delete()
        # TODO: Ask to delete resources
        self.delete()
        
        
#    class Meta:
#        permissions = (
#                       ("can_edit_page","Can edit page, edit include disable page"),
#                       ("can_erase_page","Can erase page, the page delete from database"),
#                       ("can_enable_page","Can enable page"),
#                       ("can_disable_page","Can disable page"),
#                       ("can_create_page","Can create new pages"),
#                       ("can_admin_page","Admin pages"),
#                       )

class Collaborator(models.Model):
    page = models.ForeignKey('Page')
    user = models.ForeignKey(User)
    date = models.DateTimeField(auto_now = False,auto_now_add=True)
    lang = models.CharField( max_length=2, null=False,blank=False, choices=settings.LANGUAGES)
    version = models.PositiveIntegerField(default=0)

class PageRevision(models.Model):
    
    title = models.CharField( max_length=60, null=False,blank=False)
    content = models.TextField(null=False)
    version = models.PositiveIntegerField(default=0)
    lang = models.CharField( max_length=2, null=False,blank=False, choices=settings.LANGUAGES)
    onCreate = models.DateTimeField(auto_now = False,auto_now_add=True)
    #noteChange = models.TextField()
    
    page = models.ForeignKey(Page,related_name='revision')
    
    def save(self):
        self.title = self.title.strip()
        self.content = self.content.strip()
        super(PageRevision,self).save()


#from django.contrib import admin

#admin.site.register([Page,PageRevision])
#admin.site.register(Page)
#admin.site.unregister(PageRevision)


#admin.site.register(Collaborator)


